package com.heima.wemedia.config;

import com.alibaba.fastjson.JSON;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.entity.WmUser;
import com.heima.wemedia.util.WmThreadLocalUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 微服务拦截器
 */

@Component
public class WmInteractor implements HandlerInterceptor {
/**
     * 判断请求是否经过网关验证,只放行经过网关验证通过的请求,即已登录过用户的请求
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String userId = request.getHeader("userId");
        if (StringUtils.isNotBlank(userId)) {
            WmUser user = new WmUser();
            user.setId(Long.valueOf(userId));
            WmThreadLocalUtil.set(user);
            return HandlerInterceptor.super.preHandle(request, response, handler);
        }
        //userId为空代表请求不合法,没经过网关且未登录
        //401代表无权限
        response.setStatus(HttpStatus.SC_UNAUTHORIZED);
        ResponseResult responseResult = ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(JSON.toJSONString(responseResult));
        //返回false代表该请求被拦截
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

        WmThreadLocalUtil.remove();
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

 /*  @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }*/

    // TODO: 2022/4/10 0010  
}
